import React from "react";
import {Upload, Button, message} from "antd";
import {ImportOutlined} from "@ant-design/icons";
import * as XLSX from "xlsx";

interface DataType {
  key: React.Key;
  main: string;
  number: string;
  name: string;
  attribute: string;
  location: string;
  address: string;
  ownership: string;
  isImportant: boolean;
  note: string;
  editStatus?: boolean;
}

interface ExcelUploadProps {
  onDataUpload: (data: DataType[]) => void;
}

const mainOptions: { label: string; value: string }[] = [
  {
    label: "全部",
    value: "1",
  },
  {
    label: "仓库1",
    value: "2",
  },
  {
    label: "仓库2",
    value: "3",
  },
];

const attributeOptions: { label: string; value: string }[] = [
  {
    label: "生产仓库（车间）",
    value: "1",
  },
  {
    label: "存储仓库",
    value: "2",
  },
  {
    label: "第三方仓库",
    value: "3",
  },
];

const locationOptions: { label: string; value: string }[] = [
  {
    label: "产地附近",
    value: "1",
  },
  {
    label: "客户附近",
    value: "2",
  },
  {
    label: "其他",
    value: "3",
  },
];

const ownershipOptions: { label: string; value: string }[] = [
  {
    label: "自有",
    value: "1",
  },
  {
    label: "租用",
    value: "2",
  },
  {
    label: "第三方代管",
    value: "3",
  },
];

const importantOptions: { label: string; value: boolean }[] = [
  {
    label: "是",
    value: true,
  },
  {
    label: "否",
    value: false,
  },
];

const ExcelUpload: React.FC<ExcelUploadProps> = ({onDataUpload}) => {
  const handleFileChange = (info: any) => {
    const selectedFile = info.file;
    if (selectedFile) {
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      parseExcel(selectedFile);
    }
  };

  // 解析用户上传的Excel文件
  const parseExcel = (file: File) => {
    const reader = new FileReader();
    try {
      // 读取用户选择的文件内容，当文件读取完成时，回调onload函数
      reader.onload = (event) => {
        // 将内容以字符串形式读取
        const data = event.target?.result as string;
        const workbook = XLSX.read(data, {type: "binary"});
        const sheetName = workbook.SheetNames[0];
        const sheet = workbook.Sheets[sheetName];
        // 将Excel表格转换为JSON对象数组
        const jsonData = XLSX.utils.sheet_to_json(sheet, {header: 1});
        // 处理JSON数据并映射到自定义的数据结构DataType[]，对原始JSON数据(去表头)进行遍历，一个row就是一个DataType类型对象
        const dataArray: DataType[] = jsonData.slice(1).map((row: any, index: number) => {
          return {
            key: index + 1,
            main: mainOptions.find((item) => item.value === row[1] || item.label === row[1])?.label || row[1],
            number: row[2],
            name: row[3],
            attribute: attributeOptions.find((item) => item.value === row[4] || item.label === row[4])?.label || row[4],
            location: locationOptions.find((item) => item.value === row[5] || item.label === row[5])?.label || row[5],
            address: row[6],
            ownership: ownershipOptions.find((item) => item.value === row[7] || item.label === row[7])?.label || row[7],
            isImportant:
              importantOptions.find((item) => item.value === row[8] || item.label === row[8])?.label || row[8],
            note: row[9],
            // 构建一个包含所有字段的新对象，并设置editStatus为false
            editStatus: false,
          };
        });
        // console.log(dataArray);
        onDataUpload(dataArray);
        message.success("导入成功");
      };
      reader.readAsBinaryString(file);
    } catch (error) {
      // console.error(error);
      message.error("导入失败");
    }
  };

  return (
    <Upload accept=".xlsx, .xls" showUploadList={false} beforeUpload={() => false} onChange={handleFileChange}>
      <Button type="primary" icon={<ImportOutlined/>}>
        Excel导入
      </Button>
    </Upload>
  );
};

export default ExcelUpload;
